import { AnyAction } from 'redux'
import * as TYPES from '../action-types'
import LOGIN_TYPES from '../../typings/login-types'

export interface ProfileState {
    loginState: LOGIN_TYPES // 当前用户登录的状态
    user: any // 用户信息
    error: string | null
}

let initailState: ProfileState = {
    loginState: LOGIN_TYPES.UN_VALIDATE,
    user: null,
    error: null
}

export default function (state: ProfileState = initailState, action: AnyAction): ProfileState {
    switch (action.type) {
        case TYPES.VALIDATE:
            if (action.payload.success) {
                return {
                    ...state,
                    loginState: LOGIN_TYPES.LOGINED,
                    user: action.payload.data, // 设置用户名
                    error: null
                }
            } else {
                return {
                    ...state,
                    loginState: LOGIN_TYPES.UNLOGIN,
                    user: null, // 设置用户名
                    error: action.payload
                }
            }
        case TYPES.LOGOUT:
            return {
                ...state,
                loginState: LOGIN_TYPES.UN_VALIDATE,
                user: null,
                error: null
            }
        case TYPES.CHANGE_AVATAR:
            return { ...state, user: { ...state.user, avatar: action.payload } }
        default:
            return state
    }
}